<?php
namespace App\Http\Middleware;

use App\Model\Operation;
use App\Repository\Contracts\OperationInterface;
use App\Support\Helper\CommonHelper;
use Closure;
use Illuminate\Http\Request;
use Auth;

/**
 * 操作日志
 *
 * @Author:: HuangYin
 * @DateTime: 2017/6/7 22:35
 */
class OperationMiddleware
{
    /**
     * @var Request
     */
    protected $requests;

    /**
     * @var OperationInterface
     */
    protected $operation;

    /**
     * @var int
     */
    protected $uid;

    /**
     * OperationMiddleware constructor.
     *
     * @param Request $requests
     * @param OperationInterface $operation
     */
    public function __construct(Request $requests, OperationInterface $operation)
    {
        $this->requests = $requests;

        $this->operation = $operation;

        $this->uid = CommonHelper::getToken(Auth::user())['uid'];
    }

    /**
     * Handle an incoming request.
     *
     * @param $request
     * @param Closure $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if ($this->uid) {
            $this->operation->created(
                [
                    'uid'  => $this->uid,
                    'method' => $request->method(),
                    'url'  => $request->path(),
                    'ip'   => $this->requests->getClientIp()
                ]
            );
        }

        return $next($request);
    }
}